package cn.itcast.bos.service.system.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.system.MenuDao;
import cn.itcast.bos.dao.system.PermissionRepository;
import cn.itcast.bos.dao.system.RoleDao;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	// 注入dao
	@Autowired
	private RoleDao rd;
	// 注入权限的dao
	@Autowired
	private PermissionRepository pr;
	// 注入菜单的Dao
	@Autowired
	private MenuDao md;

	@Override
	public List<Role> findByUser(User user) {
		// 判断用户如果是admin则具有所有功能
		if (user.getUsername().equals("admin")) {
			return rd.findAll();
		} else {

			return rd.findByUser(user.getId());
		}
	}

	/**
	 * 查询所有角色
	 */
	@Override
	public List<Role> finAll() {
		List<Role> list = rd.findAll();
		return list;
	}

	/**
	 * 保存角色
	 */
	@Override
	public void save(Role model, String[] permissionIds, String menuIds) {
		rd.save(model);
		// 给角色关联权限
		if (permissionIds != null) {
			// 遍历数组
			for (String permissionId : permissionIds) {
				// 通过数据库查找出对应的角色
				Permission permission = pr.findOne(Integer
						.parseInt(permissionId));
				model.getPermissions().add(permission);
			}
		}
		// 关联菜单
		if (StringUtils.isNoneBlank(menuIds)) {
			// 分割字符串
			String[] split = menuIds.split(",");
			// 遍历数组
			for (String string : split) {
				// 查找对应的菜单
				Menu menu = md.findOne(Integer.parseInt(string));
				model.getMenus().add(menu);
			}
		}
	}

}
